import request from '@/plugins/request'
import { IResponseData } from '@/types/request-base'
import { json2FormData, createDownload } from '@/utils'

/**
 *  获取主键id
 * @returns
 */
export function queryId() {
  return request<IResponseData>({
    url: '/app/v1/common/getId',
    method: 'get'
  })
}

/**
 *  通过typeCode获取附件模板Id
 * @returns
 */
export const getAttachmentTemplate = async (typeCode: string) => {
  if ([null, undefined, ''].includes(typeCode)) {
    return ''
  }
  const filtersRaw = [
    { id: 'typeCode', property: 'typeCode', operator: '=', value: typeCode },
    { id: 'enable', property: 'enable', operator: '=', value: '1' }
  ]
  const data = new FormData()
  data.append('filtersRaw', JSON.stringify(filtersRaw))
  data.append('pageFlag', 'false')
  const res = await request<IResponseData>({
    url: '/app/v1/configAttachmentTemplate/page',
    method: 'POST',
    data
  })
  if (res && res.data && res.data.records && res.data.records.length > 0) {
    return res.data.records[0].id || ''
  }
  return ''
}

/**
 *  获取附件
 * @returns
 */
export const queryAttachmentList = async (modelId: string) => {
  let resData: any = []
  if (!modelId) return resData
  await request<IResponseData>({
    url: `/app/v1/shopAttachment/query/${modelId}`,
    method: 'get'
  }).then((res) => {
    if (res && res.data) {
      resData = res.data
    }
  })
  return resData
}

/**
 * 下载附件(通过url获取buffer)
 * @param {string} e 附件数据
 */
export const downAttachment = (e: any) => {
  return request({
    url: `/app/v1/file/downloadFile?fileName=${e.attachmentUrl}`,
    method: 'POST',
    responseType: 'arraybuffer'
  }).then((res: any) => {
    createDownload(res.data, e.attachmentName, false)
  })
}
/**
 * 模板附件分页查询
 * @param {string} e 附件数据
 */
export const getTemplateAttachmentPage = ({ name, page, rows }: any) => {
  const filtersRaw = []
  if (name) {
    filtersRaw.push({ id: 'attachmentName0', property: 'attachmentName', operator: 'like', value: name })
  }
  const params = {
    page,
    rows,
    pageFlag: true,
    // sort: 'createTime',
    // order: 'DESC',
    filtersRaw: JSON.stringify(filtersRaw)
  }
  const data = json2FormData(params)
  return request({
    url: `/app/v1/configAttachmentTemplate/queryAttachmentPage`,
    method: 'POST',
    data
  })
}

/**
 * 获取档案维护(主数据)查询数据
 * @param {object} data 参数
 */
export const queryMdmServiceCustDocDefList = async (code: any) => {
  const filtersRaw = []
  if (code) {
    filtersRaw.push({ id: 'custDocCode0', property: 'custDocCode', operator: '=', value: code })
  }
  const params = {
    page: 1,
    rows: 50,
    pageFlag: false,
    filtersRaw: JSON.stringify(filtersRaw)
  }
  const data = json2FormData(params)

  let resData: any = []
  await request<IResponseData>({
    method: 'post',
    url: `/app/v1/mdmService/custDocDef/page`,
    data
  }).then((res) => {
    if (res && res.data) {
      resData = res.data?.records || []
    }
  })
  return resData
}
